<?php

namespace app\index\controller;

use app\index\model\Comments;
use app\index\model\Goods;
use app\index\model\OrderDetail;
use app\index\model\Orders;
use app\index\model\Pictures;
use app\index\model\Spu;
use think\Controller;

class CommentCtl extends Controller
{
    /*
     * 新增评论
     */
    public function addComment()
    {
        // 对于某件商品，一个用户只能发布一条评论
        $count = Comments::where(['gid' => input('gid'), 'uid' => input('uid')])->count('id');
        if ($count >= 1) {
            return json(['msg' => '只能发表一条评论！', 'code' => '1']);
        }

        // 对于某件商品，用户必须购买过才能评论
        $bought = false;
        $orderIds = Orders::where('uid', input('uid'))->column('id');
        foreach ($orderIds as $oi) {
            $spuIds = OrderDetail::where('order_id', $oi)->column('spuid');
            foreach ($spuIds as $si) {
                if (Spu::where(['id' => $si, 'gid' => input('gid')])->find() != null) {
                    $bought = true;
                    break 2;
                }
            }
        }
        if (!$bought) {
            return json(['msg' => '只有购买了本件商品才能发表评论！', 'code' => '2']);
        }

        Comments::create([
            'gid' => input('gid'),
            'uid' => input('uid'),
            'content' => input('content'),
            'stars' => input('stars'),
            'time' => time()
        ]);
        return json(['msg' => '评论成功！', 'code' => 20000]);
    }

    /*
     * 根据评论 id 删除评论
     */
    public function delComment()
    {
        Comments::destroy(input('id'));
        return json(['msg' => '删除成功！', 'code' => 20000]);
    }

    /*
     * 获取某商品的所有评论
     */
    public function getCommentsByGid()
    {
        $res['data'] = Comments::where('gid', input('gid'))->with(['user' => function ($query) {
            $query->field('id,email,phone,username,avatar');
        }])->select();
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 获取用户的所有评论
     */
    public function getCommentsByUid()
    {
        $res['data'] = Comments::where('uid', input('uid'))->select();
        foreach ($res['data'] as $r) {
            $r['picture'] = Pictures::where(['gid' => $r['gid'], 'type' => 0])->value('url');
            $r['goods'] = Goods::where(['id' => $r['gid']])->value('name');
        }
        $res['code'] = 20000;
        return json($res);
    }
}